import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { ProductService } from '../share/product.service';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {

  private formModel: FormGroup;
  private categorys: Array<string>;

  constructor(
    private productService: ProductService
  ) {
    let fb = new FormBuilder();
    this.formModel = fb.group({
      title: ['', Validators.minLength(3)],
      price: [null, this.positiveNumberValidator],
      category: ['-1']
    });
  }

  ngOnInit() {
    this.getAllCategorys();
  }

  /**
   * 校验通过，console 显示表单的数据
   */
  onSearch() {
    console.log('onSearch() 执行..');
    if (this.formModel.valid) {
      this.productService.searchEvent.emit(this.formModel.value);
      // console.log(this.formModel);
      console.log('表单值：', this.formModel.value);
    }
  }

  /**
   * 获取所有商品分类
   */
  getAllCategorys() {
    this.categorys = this.productService.getAllCategorys();
  }

  /**
   * 价格是否 是 正数的校验
   * @param control 
   */
  private positiveNumberValidator(control: FormControl): any {
    console.log('positiveNumberValidator() 执行..');
    // 没有传值 或者 值是正数
    if (control.value) {
      let price = parseInt(control.value);
      if (price >= 0) {
        console.log('价格正确...');
      } else {
        console.log('价格错误...');
        // 传入的值是负数，校验失败
        // 返会的值不能是 positiveCheck: false，其它返回值和true效果一样，否者页面不能获取数据,因为返回null和false的效果一样
        return { positiveCheck: '请输入正数...' };
      }
    }
    return null;
  }
}
